// 创建用户相关的小仓库
import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import cloneDeep from "lodash/cloneDeep";
import router from "../../router";
// 引入接口
import { reqLogin, reqUserInfo, reqLogOut } from "../../api/user/index";
// 引入数据类型
import type { LoginFormData } from "../../api/user/type";
import { UserStater } from "./type/type";
// 引入操作本地存儲的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "../../utils/token";

// 引入路由（常量路由）
import { constantRoute, asyncRoute, anyRoute } from "../../router/routers";

let dynamicRoutes: RouteRecordRaw[] = [];

// 用于过滤当前用户需要展示的异步路
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

// 定义变量
let useUserStore = defineStore("User", {
  // 小仓库存储数据的地方
  state: (): UserStater => {
    return {
      //用户信息
      userInfo: {},
      //用户token
      token: GET_TOKEN() || "",
      menuRoutes: constantRoute, // 仓库存储生产菜单需要的数组（路由）
      avatar: "",
      userName: "",
      // 存储当前用户是否包含某一个按钮
      buttons: [],
    };
  },
  //   异步|逻辑处理的地方
  actions: {
    // 用戶登录的方法
    async userLoin(data: LoginFormData) {
      // 登錄請求方法
      let res: any = await reqLogin(data);
      // 登录成功或者失败的处理
      if (res.code === 200) {
        // pinia仓库存储一下token
        // 由于pinia | vuex存储数据其实利用js对象
        this.token = (res.data.token as string) || (res.data as string);
        // 本地存储 持久化存储一份
        SET_TOKEN((res.data.token as string) || (res.data as string));
        // localStorage.setItem("TOKEN", (res.data.token as string));
        return "ok";
      } else {
        // 失败提示用户
        return Promise.reject(new Error(res.data || (res.message as string)));
      }
    },
    // 获取用户信息的方法
    async userInfo() {
      await reqUserInfo().then((res) => {
        if (res.code == 200) {
          this.userName = res.data.name;
          this.avatar = res.data.avatar;
          this.buttons = res.data.buttons;
          // this.userInfo = res.data.checkUser;
          // 配置用户路由权限
          // 计算当前用户需要展示的异步路由
          const userAsyncRoute = filterAsyncRoute(
            cloneDeep(asyncRoute),
            res.data.routes,
          );
          // 菜单需要的数据整理完毕
          this.menuRoutes = [...constantRoute, ...userAsyncRoute, anyRoute];
          // 目前路由器管理的只有常量路由：用户计算完毕异步路由、任意路由动态追加
          dynamicRoutes = [...userAsyncRoute, anyRoute]; // 记录动态添加的路由
          dynamicRoutes.forEach((route) => {
            router.addRoute(route); // 动态添加路由
          });
          return "ok";
        } else {
          return Promise.reject(new Error(res.message as string));
        }
      });
    },
    // 退出登录
    async userLogout() {
      // 調用登出接口
      let res = await reqLogOut();
      if (res.code == 200) {
        this.token = "";
        this.userName = "";
        this.avatar = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(res.message as string));
      }
    },
  },
  //   计算属性
  getters: {},
});

// 對外暴露小仓库的方法
export default useUserStore;
